package com.jingyuan.biz.server.testnetty;

import com.jingyuan.biz.event.EventManager;
import com.jingyuan.biz.event.BaseEvent;
import lombok.Getter;
import lombok.Setter;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * 协调服务器
 */
@Setter
@Getter
public class HarmonyServer {
    private EventManager eventManager;
    private ThreadPoolExecutor executor;

    public void startServer() {
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(512);
        RejectedExecutionHandler policy = new ThreadPoolExecutor.DiscardPolicy();
//        //确定线程池大小
//        int minPoolSize = configure.getMinPoolSize() > 1 ? configure.getMinPoolSize() : 2;
//        int maxPoolSize = configure.getMaxPoolSize() < 20 ? configure.getMaxPoolSize() : 20;
//        if (maxPoolSize < minPoolSize) {
//            maxPoolSize = minPoolSize;
//        }

        this.executor = new ThreadPoolExecutor(5, 20,
                0, TimeUnit.SECONDS,
                queue,
                policy);
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            while (true) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                                   public void run() {
                                       System.out.println("-------注册中心服务器运行中--------");
                                   }
                               }, 1000, 5000
                );
                Socket socket = serverSocket.accept();
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        BaseEvent source=new BaseEvent();
                        eventManager.dispatch(source);
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
